package study.jsm.com.myapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

import study.jsm.com.myapplication.Utils.ToastUtils;

import static study.jsm.com.myapplication.Utils.ToastUtils.showToast;

public class MainActivity extends Activity {

    String fruit[] = {"苹果", "香蕉", "樱桃", "葡萄", "芒果", "橘子", "梨子", "菠萝", "草莓", "西瓜"};
    int fruitImages[] = {R.drawable.apple_pic, R.drawable.banana_pic, R.drawable.cherry_pic, R.drawable.grape_pic, R.drawable.mango_pic, R.drawable.orange_pic, R.drawable.pear_pic, R.drawable.pineapple_pic, R.drawable.strawberry_pic, R.drawable.watermelon_pic};
    GridView gv_items;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gv_items = findViewById(R.id.gv_items);
        gv_items.setAdapter(new MyAdapter(this, fruit, fruitImages));
        gv_items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showToast(MainActivity.this, fruit[i]);
            }
        });
    }
}

class MyAdapter extends BaseAdapter {

    String fruit[];
    int fruitImages[];
    Context context;

    MyAdapter(Context context, String[] fruit, int[] fruitImages) {
        this.context = context;
        this.fruit = fruit;
        this.fruitImages = fruitImages;
    }

    @Override
    public int getCount() {
        return fruit.length;
    }

    @Override
    public Object getItem(int i) {
        return fruit[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rootView = View.inflate(context, R.layout.item_fruit, null);
        TextView tv_fruit_name = rootView.findViewById(R.id.tv_fruit_name);
        tv_fruit_name.setText(getItem(i).toString());
        ImageView iv_fruit = rootView.findViewById(R.id.iv_fruit);
        iv_fruit.setImageResource(fruitImages[i]);
        return rootView;

    }
}